#!/bin/bash

# Weather System 日志管理工具

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 显示帮助信息
show_help() {
    echo "Weather System 日志管理工具"
    echo ""
    echo "用法: $0 [COMMAND] [OPTIONS]"
    echo ""
    echo "命令:"
    echo "  view [service]     - 查看服务日志"
    echo "  follow [service]   - 实时跟踪日志"
    echo "  search <term>      - 搜索日志内容"
    echo "  errors             - 查看错误日志"
    echo "  export [date]      - 导出指定日期的日志"
    echo "  stats              - 显示日志统计信息"
    echo "  cleanup [days]     - 清理指定天数前的日志"
    echo "  grafana            - 打开Grafana日志面板"
    echo ""
    echo "服务名称:"
    echo "  api, frontend, rabbitmq, redis, loki, promtail, grafana"
    echo ""
    echo "选项:"
    echo "  --lines N          - 显示最后N行日志 (默认: 100)"
    echo "  --since TIME       - 显示指定时间后的日志"
    echo "  --level LEVEL      - 过滤日志级别 (ERROR, WARN, INFO, DEBUG)"
    echo ""
    echo "示例:"
    echo "  $0 view api --lines 50"
    echo "  $0 follow api"
    echo "  $0 search \"数据采集失败\""
    echo "  $0 errors --since \"1h\""
    echo "  $0 export 2024-01-15"
}

# 获取Docker Compose文件
get_compose_file() {
    if [ -f "$PROJECT_DIR/docker-compose.yml" ] && docker-compose -f "$PROJECT_DIR/docker-compose.yml" ps | grep -q "weather-system"; then
        echo "$PROJECT_DIR/docker-compose.yml"
    elif [ -f "$PROJECT_DIR/docker-compose.dev.yml" ]; then
        echo "$PROJECT_DIR/docker-compose.dev.yml"
    else
        echo ""
    fi
}

# 获取容器名称
get_container_name() {
    local service=$1
    local compose_file=$(get_compose_file)
    
    case $service in
        "api"|"backend")
            if [[ $compose_file == *"dev.yml" ]]; then
                echo "weather-system-api" # 开发环境运行在宿主机
            else
                echo "weather-system-api"
            fi
            ;;
        "frontend"|"react")
            echo "weather-system-frontend"
            ;;
        "rabbitmq"|"mq")
            if [[ $compose_file == *"dev.yml" ]]; then
                echo "weather-rabbitmq-dev"
            else
                echo "weather-rabbitmq"
            fi
            ;;
        "redis")
            if [[ $compose_file == *"dev.yml" ]]; then
                echo "weather-redis-dev"
            else
                echo "weather-redis"
            fi
            ;;
        "loki")
            if [[ $compose_file == *"dev.yml" ]]; then
                echo "weather-loki-dev"
            else
                echo "weather-loki"
            fi
            ;;
        "promtail")
            if [[ $compose_file == *"dev.yml" ]]; then
                echo "weather-promtail-dev"
            else
                echo "weather-promtail"
            fi
            ;;
        "grafana")
            if [[ $compose_file == *"dev.yml" ]]; then
                echo "weather-grafana-dev"
            else
                echo "weather-grafana"
            fi
            ;;
        *)
            echo ""
            ;;
    esac
}

# 查看日志
view_logs() {
    local service=${1:-"all"}
    local lines=${2:-100}
    local since=${3:-""}
    
    local compose_file=$(get_compose_file)
    if [ -z "$compose_file" ]; then
        echo -e "${RED}错误: 找不到运行中的Docker Compose服务${NC}"
        exit 1
    fi

    if [ "$service" = "all" ]; then
        echo -e "${BLUE}查看所有服务日志 (最近 $lines 行)${NC}"
        if [ -n "$since" ]; then
            docker-compose -f "$compose_file" logs --tail="$lines" --since="$since"
        else
            docker-compose -f "$compose_file" logs --tail="$lines"
        fi
    else
        local container=$(get_container_name "$service")
        if [ -z "$container" ]; then
            echo -e "${RED}错误: 未知的服务名称: $service${NC}"
            exit 1
        fi
        
        echo -e "${BLUE}查看 $service 服务日志 (最近 $lines 行)${NC}"
        if [ -n "$since" ]; then
            docker logs --tail="$lines" --since="$since" "$container"
        else
            docker logs --tail="$lines" "$container"
        fi
    fi
}

# 实时跟踪日志
follow_logs() {
    local service=${1:-"all"}
    
    local compose_file=$(get_compose_file)
    if [ -z "$compose_file" ]; then
        echo -e "${RED}错误: 找不到运行中的Docker Compose服务${NC}"
        exit 1
    fi

    if [ "$service" = "all" ]; then
        echo -e "${BLUE}实时跟踪所有服务日志 (Ctrl+C 退出)${NC}"
        docker-compose -f "$compose_file" logs -f
    else
        local container=$(get_container_name "$service")
        if [ -z "$container" ]; then
            echo -e "${RED}错误: 未知的服务名称: $service${NC}"
            exit 1
        fi
        
        echo -e "${BLUE}实时跟踪 $service 服务日志 (Ctrl+C 退出)${NC}"
        docker logs -f "$container"
    fi
}

# 搜索日志
search_logs() {
    local search_term=$1
    local compose_file=$(get_compose_file)
    
    if [ -z "$search_term" ]; then
        echo -e "${RED}错误: 请提供搜索关键词${NC}"
        exit 1
    fi
    
    echo -e "${BLUE}搜索日志: '$search_term'${NC}"
    
    if [ -n "$compose_file" ]; then
        docker-compose -f "$compose_file" logs | grep -i --color=always "$search_term"
    else
        # 搜索本地日志文件
        find "$PROJECT_DIR/logs" -name "*.log" -exec grep -l -i "$search_term" {} \; 2>/dev/null | while read file; do
            echo -e "${GREEN}发现匹配: $file${NC}"
            grep -n -i --color=always "$search_term" "$file" | head -10
            echo ""
        done
    fi
}

# 查看错误日志
view_errors() {
    local since=${1:-"1h"}
    local compose_file=$(get_compose_file)
    
    echo -e "${RED}查看错误日志 (最近 $since)${NC}"
    
    if [ -n "$compose_file" ]; then
        docker-compose -f "$compose_file" logs --since="$since" | grep -i --color=always -E "(error|exception|fail|critical)"
    else
        # 查看本地错误日志文件
        find "$PROJECT_DIR/logs" -name "*errors*.log" -exec tail -100 {} \;
    fi
}

# 导出日志
export_logs() {
    local date=${1:-$(date +%Y-%m-%d)}
    local export_dir="$PROJECT_DIR/logs/exports"
    
    mkdir -p "$export_dir"
    
    echo -e "${BLUE}导出 $date 的日志到 $export_dir${NC}"
    
    local compose_file=$(get_compose_file)
    if [ -n "$compose_file" ]; then
        # 导出容器日志
        docker-compose -f "$compose_file" logs --since="$date" --until="$(date -d "$date + 1 day" +%Y-%m-%d)" > "$export_dir/weather-system-$date.log"
    fi
    
    # 复制本地日志文件
    find "$PROJECT_DIR/logs" -name "*$date*.log" -exec cp {} "$export_dir/" \; 2>/dev/null
    
    echo -e "${GREEN}日志导出完成: $export_dir${NC}"
    ls -la "$export_dir"
}

# 显示统计信息
show_stats() {
    echo -e "${BLUE}Weather System 日志统计${NC}"
    echo ""
    
    # API统计
    echo -e "${YELLOW}API日志统计:${NC}"
    curl -s "http://localhost:5197/api/logs/stats" | jq . 2>/dev/null || echo "API未运行或统计不可用"
    echo ""
    
    # 容器状态
    local compose_file=$(get_compose_file)
    if [ -n "$compose_file" ]; then
        echo -e "${YELLOW}容器状态:${NC}"
        docker-compose -f "$compose_file" ps
        echo ""
    fi
    
    # 本地日志文件
    if [ -d "$PROJECT_DIR/logs" ]; then
        echo -e "${YELLOW}本地日志文件:${NC}"
        ls -lah "$PROJECT_DIR/logs/" | head -10
    fi
}

# 清理日志
cleanup_logs() {
    local days=${1:-30}
    
    echo -e "${YELLOW}清理 $days 天前的日志文件${NC}"
    
    if [ -d "$PROJECT_DIR/logs" ]; then
        find "$PROJECT_DIR/logs" -name "*.log" -mtime +$days -delete
        echo -e "${GREEN}本地日志清理完成${NC}"
    fi
    
    # 清理Docker日志
    docker system prune -f --filter "until=${days}h"
    echo -e "${GREEN}Docker日志清理完成${NC}"
}

# 打开Grafana
open_grafana() {
    local grafana_url="http://localhost:3001"
    
    echo -e "${BLUE}打开Grafana日志面板${NC}"
    echo "URL: $grafana_url"
    echo "用户名: admin"
    echo "密码: admin123"
    
    # 尝试打开浏览器
    if command -v xdg-open > /dev/null; then
        xdg-open "$grafana_url"
    elif command -v open > /dev/null; then
        open "$grafana_url"
    else
        echo "请手动打开浏览器访问: $grafana_url"
    fi
}

# 主逻辑
case ${1:-help} in
    "view")
        view_logs "$2" "$3" "$4"
        ;;
    "follow"|"tail")
        follow_logs "$2"
        ;;
    "search"|"grep")
        search_logs "$2"
        ;;
    "errors"|"error")
        view_errors "$2"
        ;;
    "export")
        export_logs "$2"
        ;;
    "stats"|"status")
        show_stats
        ;;
    "cleanup"|"clean")
        cleanup_logs "$2"
        ;;
    "grafana"|"ui")
        open_grafana
        ;;
    "help"|"-h"|"--help")
        show_help
        ;;
    *)
        echo -e "${RED}错误: 未知命令 '$1'${NC}"
        echo ""
        show_help
        exit 1
        ;;
esac